36

让我们先回忆一下ES6的对象解构,本文介绍各种ES6的对象解构用法,你用过哪一种?

最基本的解构

在对象中提取某个字段

const user = {
  id: 123,
  name: 'hehe'
};
const {name} = user;
console.log(name); //prints: hehe

解构并使用别名

有时接口定义的字段往往带有下划线,但我们的前端更便好于驼峰式命名,那么可以使用别名(rename):

const user = {
  id: 123,
  nick_name: 'hehe'
};
const {nick_name: nickName} = user;
console.log(nickName); //prints: hehe

解构嵌套对象

有时我们会遇到嵌套对象,如果我们了解未足够多时,会写出这种解构:

const user = {
  id: 123,
  name: 'hehe',
  education: {
    degree: 'Masters'
  }
};

// 假设我们要提取degree
const {education} = user;
const {degree} = education;

我们会写两行,一层层的剥开,明显繁琐,如果这个对象有三四层结构那简直无法入目。其实可以用解构一步到位的:

const user = {
  id: 123,
  name: 'hehe',
  education: {
    degree: 'Masters'
  }
};
const {education: {degree}} = user;
console.log(degree); //prints: Masters

没错,就是比别名方法多了一个{ }

如果没有外层怎么办

假设要解构的数据是由接口返回的,由于某种原因会导致某个字段丢失。我们会往往遇到这种意外:

const user = {
  id: 123,
  name: 'hehe'
};
const {education: {degree}} = user;  // TypeError: Cannot match against 'undefined' or 'null'.

这时你是否会觉得还是我们原始的方法好使:

const education = user || {};
const degree = education.degree;

其实,神奇的解构可以让你定义一个缺省值,这样,我们不仅可以达到数据防御的目的,而且告别啰嗦的写法了:

const user = {
  id: 123,
  name: 'hehe'
};

const {
    education: {
        degree
    } = {}
} = user;
console.log(degree); //prints: undefined

这明显是一股清流啊。

更深层次的对象怎么办?

const user = {
  id: 123,
  name: 'hehe'
};

const {
    education: {
        school: {
            name
        }
    } = {}
} = user;  // TypeError: Cannot match against 'undefined' or 'null'.

这里外层对education设置缺省值,但里面的school不存在,依然会报错。
我们第一种办法就是继续对school设置缺省值为{}:

const user = {
  id: 123,
  name: 'hehe'
};
const {
    education: {
        school: {
            name
        } = {}
    } = {}
} = user;
console.log(name); //prints: undefined

另一种办法就是直接给education缺省值设置为{school: {}}:

const user = {
  id: 123,
  name: 'hehe'
};
const {
    education: {
        school: {
            name
        }
    } = {school: {}}
} = user;
console.log(name); //prints: undefined

这两种方法看似都可以,但如果要给学校名称school.name一个缺省值呢?如果是第一种方法,会写成这样:

const user = {
  id: 123,
  name: 'hehe'
};
const {
    education: {
        school: {
            name = 'NB'
        } = {}
    } = {}
} = user;
console.log(name); //prints: NB

你数数看,这有多少个“=”号吗?啰嗦得不行,再看第二种方法:

const user = {
  id: 123,
  name: 'hehe'
};
const {
    education: {
        school: {
            name
        }
    } = {
        school: {
            name: 'NB'
        }
    }
} = user;
console.log(name); //prints: NB

这样整体给education设置一个缺省值,可读性更强,这又是一股清流。
在代码中灵活使用解构不仅可以使代码简洁可读,而且逼格大大提升。


zzbo
114 声望6 粉丝